//////////////////////////////////////////////////////////////////////////////////
//	 Copyright 2011 by Yosef Grabivker, ryuho@homenetworksoft.com
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//////////////////////////////////////////////////////////////////////////////////

#ifndef __TELNET_LINK_YG_H__
#define __TELNET_LINK_YG_H__

#include "ilink.h"
#include "rtelnetsocket.h"

class CTelnetLink: public ILink
{
public:
							CTelnetLink(void);
	virtual					~CTelnetLink(void);
public:
	virtual void			Create();
	virtual void			Connect(const CONPARAMS& con);
	virtual RTSTRING		ReadFile(const wxString& strPath);
	virtual RTSTRING		SendCmd(const wxString& strScript, unsigned int lDelay=RT_MAX_READ_TIMEOUT);
	virtual RTSTRING		SendSymb(const wxString& str, unsigned int lDelay=RT_MAX_READ_TIMEOUT);

	virtual void			CleanUp();
	virtual bool			HaveGrep() { return m_bGrepSupported; }
	virtual RTSTRING		GetLog()   { return m_strLog;		  }
	virtual bool			IsLoggedOn();


protected:
	RTSTRING				ReadString(wxUint32 lLinesExpected=-1, wxUint32 lTimeOut=RT_MAX_READ_TIMEOUT);
	int						RemoveANSISequence(char* buf, int nRead);
	void					SendString(const wxString& strStr);
	void					SendEnter();
	bool					WaitForPrompt();
	void					AddToLog(const char* szStr);
	bool					IsPromptChar(char c);
	wxString				GetEnterSeq();
	RTSTRING				WaitForLoginString( const wxString& strLogin );
	void					EnableTelnetByHTTP(const CONPARAMS& con);

private:
	struct CSockGuard
	{
		CSockGuard():m_pSocket(NULL), m_proto(cPROTOCOLTelnet) {}
		~CSockGuard()
		{
			CleanUp();
		}

		void CleanUp()
		{
			delete m_pSocket;
			m_pSocket = NULL;
		}

		void SetType(cPROTOCOL type) { m_proto=type; }

		CRTSocket* operator->()
		{
			return m_pSocket?m_pSocket:CreateNewSocket();
		}

	protected:
		CRTSocket* CreateNewSocket();

	private:
		CRTSocket* m_pSocket;
		cPROTOCOL  m_proto;
	};

	CSockGuard				m_sock;
	bool					m_bGrepSupported;
	char					m_chPrompt;
	bool					m_bLogedOn;
	RTSTRING				m_strLog;
};

#endif //__TELNET_LINK_YG_H__